package com.aqie.haikang.dorm.service.impl;

import com.aqie.haikang.dorm.common.R;
import com.aqie.haikang.dorm.dao.HkEnterRepository;
import com.aqie.haikang.dorm.entity.dto.HkEnterDTO;
import com.aqie.haikang.dorm.service.IHkEnterService;
import com.ejlchina.okhttps.HTTP;
import com.ejlchina.okhttps.HttpResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @Author aqie
 * @Date 2021/12/11 9:38
 * @desc
 */
@Slf4j
@AllArgsConstructor
@Service
public class HkEnterServiceImpl implements IHkEnterService {
    private final HkEnterRepository hkEnterRepository;

    private final HTTP okhttps;

    @Override
    public List<HkEnterDTO> findCurrentAll() {
        List<HkEnterDTO> listRaw = hkEnterRepository.findCurrentAll();
        // 数据处理
        List<HkEnterDTO> list =progressData(listRaw);
        return list;
    }

    @Override
    public boolean postData() {
        List<HkEnterDTO> list = findCurrentAll();
        if(list.size() == 0){
            log.info("当天无数据");
            return false;
        }
        log.info("post data {}", list);
        HttpResult result = okhttps.sync("dorm/hkenter/saveBatch")
                .setBodyPara(list)
                .bodyType("json")
                .post();
        boolean success = result.getBody().toBean(R.class).isSuccess();

        return success;
    }

    private List<HkEnterDTO> progressData(List<HkEnterDTO> list) {
        // 1. 时间 大于 18:00 GROUP BY分组取最新一条数据
        log.info("时间 大于 18:00 {}", list.size()); // 1067 -> 828
        // 2. 时间重复
        ArrayList<HkEnterDTO> noRepeatList = list.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                        // 用户code和时间去重
                        Comparator.comparing(h -> h.getCode()+h.getCreateTime())
                )), ArrayList::new
        ));
        log.info("时间 重复 {}", noRepeatList.size()); // 807 -> 952 -> 828
        // 3. 一分钟内重复 赵韵涵
        // 4. 当天重复数据
        // 5. 最后一次是出还是进
        return noRepeatList;

    }
}
